package com.ease.framework.gef4p.figures.impl.edge {
   import com.ease.framework.gef4p.figures.edge.IBendAnchor;
   import com.ease.framework.gef4p.figures.edge.IEdgeFigure;

   import mx.collections.ArrayCollection;
   import mx.core.UIComponent;

   public class BendAnchorManager extends AbstractEdgeListener {
      public var bendAnchors:ArrayCollection = new ArrayCollection();

      public function BendAnchorManager() {
         super();
      }

      override public function afterCreateChildren(edgeFigure:IEdgeFigure):void {
         var source:Bend = (edgeFigure as EdgeFigure).getSourceBend();
         while (source != null && source.getNext() != null) {
            var anchor:BendAnchor = new BendAnchor(this, source, source.getNext());
            bendAnchors.addItem(anchor);
            edgeFigure.addChild(anchor);
            anchor.visible = false;

            if (source.getNext().getNext() != null) {
               anchor = new BendAnchor(this, source.getNext(), source.getNext());
               bendAnchors.addItem(anchor);
               edgeFigure.addChild(anchor);
               anchor.visible = false;
            }
            source = source.getNext();
         }
      }

      override public function select(edgeFigure:IEdgeFigure):void {
         for each (var bendAnchor:IBendAnchor in bendAnchors) {
            bendAnchor.visible = edgeFigure.isSelected;
         }
      }

      public function findBendAnchor(source:Bend, target:Bend):BendAnchor {
         for each (var bendAnchor:BendAnchor in bendAnchors) {
            if (bendAnchor.source == source && bendAnchor.target == target) {
               return bendAnchor;
            }
         }
         return null;
      }

      public function clearBendAnchors():void {
         for each (var obj:Object in bendAnchors) {
            if (obj is UIComponent) {
               UIComponent(obj).visible = false;
               UIComponent(obj).parent.removeChild(UIComponent(obj));
               IBendAnchor(obj).clear();
            }
         }
         bendAnchors.removeAll();
      }
   }
}